<?php 
/**
 * $ModDesc
 * 
 * @version		$Id: helper.php $Revision
 * @package		modules
 * @subpackage	mod_lofflashcontent
 * @copyright	Copyright (C) JAN 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>. All rights reserved.
 * @license		GNU General Public License version 2
 */
// no direct access
defined('_JEXEC') or die;

require_once JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php';

abstract class modLofFlashContentHelper {
	
	/**
	 * get list articles
	 */
	public static function getList( $params ){
		if( JVersion::isCompatible('1.6.0') ) {	
			return modLofFlashContentHelper::getListJLOneSix( $params );
		} 
		return modLofFlashContentHelper::getListJLOneFive( $params );
	}
	
	/**
	 * get the list of articles, using for joomla 1.6.x
	 */
	public static function getListJLOneFive( $params ){
		$maxTitle  = $params->get( 'max_title', '100' );
		$maxDesciption = $params->get( 'max_description', 100 );
		$openTarget = $params->get( 'open_target', 'parent' );
		$formatter  = $params->get( 'style_displaying', 'title' );
		$titleMaxChars = $params->get( 'title_max_chars', '100' );
		$descriptionMaxChars = $params->get( 'description_max_chars', 100 );
		$condition  = modLofFlashContentHelper::buildConditionQuery( $params );
		$ordering   = $params->get('ordering', 'created_asc');
		$limit 	    = $params->get( 'limit', 4 );
		$ordering   = str_replace( '_', '  ', $ordering );
		$my 	    = &JFactory::getUser();
		$aid	    = $my->get( 'aid', 0 );
		
		$data = modLofFlashContentHelper::getListQuery( $aid, $condition, $ordering, $limit );
		foreach( $data as $key => $item ){			
			if($item->access <= $aid ) {
				$data[$key]->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug, $item->sectionid));
			} else {
				$data[$key]->link = JRoute::_('index.php?option=com_user&view=login');
			}
			$item->subtitle = modLofFlashContentHelper::substring( $item->title, $titleMaxChars );
			$item->description = modLofFlashContentHelper::substring( $item->introtext, $descriptionMaxChars );
			$data[$key]->showingtext = modLofFlashContentHelper::renderText( $formatter, $item, $openTarget );
		}
		return $data;	
	}
	
	/**
	 * get the list of articles, using for joomla 1.6.x
	 */
	public static function getListJLOneSix( &$params )	{
		$formatter = $params->get( 'style_displaying', 'title' );
		$titleMaxChars = $params->get( 'title_max_chars', '100' );
		$descriptionMaxChars = $params->get( 'description_max_chars', 100 );
		
		JModel::addIncludePath(JPATH_SITE.DS.'components'.DS.'com_content'.DS.'models');
		// Get an instance of the generic articles model
		$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
		// Set application parameters in model
		$appParams = JFactory::getApplication()->getParams();
		$model->setState('params', $appParams);
		$openTarget = $params->get( 'open_target', 'parent' );
		// Set the filters based on the module params
		$model->setState('list.start', 0);
		$model->setState('list.limit', (int) $params->get('count', 5));
		$model->setState('filter.published', 1);

		// Access filter
		$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
		$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
		$model->setState('filter.access', $access);

		// Category filter
		if ($catid = $params->get('category')) {
			if( count ($catid) == 1 && !$catid[0] ) {
				$model->setState('filter.category_id', null);	
			}
			else {
				$model->setState('filter.category_id', $catid);
			}
		}

		// User filter
		$userId = JFactory::getUser()->get('id');

		$ordering  = $params->get('ordering', 'created_asc');
		$limit 	   = $params->get( 'limit', 4 );
		$ordering = split( '_', $ordering );

		$model->setState('list.ordering', $ordering[0]);
		$model->setState('list.direction', $ordering[1]);

		$items = $model->getItems();

		foreach ($items as $key => &$item) {
			$item->slug = $item->id.':'.$item->alias;
			$item->catslug = $item->catid.':'.$item->category_alias;

			if ( $access || in_array($item->access, $authorised) ) {		
				$item->link = JRoute::_(ContentRoute::article($item->slug, $item->catslug));
			}
			
			else {
				$item->link = JRoute::_('index.php?option=com_user&view=login');
			}
			$item->date = JHtml::_('date', $item->created, JText::_('DATE_FORMAT_LC2')); 
			$item->introtext = JHtml::_('content.prepare', $item->introtext);
			$item->subtitle = modLofFlashContentHelper::substring( $item->title, $titleMaxChars );
			$item->description = modLofFlashContentHelper::substring( $item->introtext, $descriptionMaxChars );
			$item->showingtext = modLofFlashContentHelper::renderText( $formatter, $item, $openTarget );
			
		}
		return $items;
	}

	/**
	 * build condition query base parameter  
	 */
	public static  function buildConditionQuery( $params ){
		
		$catids = $params->get('category','');
		if( !$catids ){
			return '';
		}
		
		$catids = !is_array($catids) ? $catids : '"'.implode('","',$catids).'"';
		$condition = ' AND  a.catid IN( '.$catids.' )';
		
		return $condition;
	}
	
	
	/**
	 * fetching data from the database 
	 */
	public static function getListQuery( $aid, $condition=null, $ordering='a.ordering', $limit=10 ){
		global $mainframe; 
	 	$db	    = &JFactory::getDBO();
		$date   =& JFactory::getDate();
		$now    = $date->toMySQL();
		
		// make sql query
		$query 	= 'SELECT a.*,cc.description as catdesc, cc.title as category_title, cc.title as cattitle,s.description as secdesc, s.title as sectitle,' 
				. ' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,'
				. ' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":",cc.id,cc.alias) ELSE cc.id END as catslug,'
				. ' CASE WHEN CHAR_LENGTH(s.alias) THEN CONCAT_WS(":", s.id, s.alias) ELSE s.id END as secslug'
				. "\n FROM #__content AS a"
				. ' INNER JOIN #__categories AS cc ON cc.id = a.catid' 
				. ' INNER JOIN #__sections AS s ON s.id = a.sectionid'
				. "\n WHERE a.state = 1"
				. "\n AND ( a.publish_up = " . $db->Quote( $db->getNullDate() ) . " OR a.publish_up <= " . $db->Quote( $now  ) . " )"
				. "\n AND ( a.publish_down = " . $db->Quote( $db->getNullDate() ) . " OR a.publish_down >= " . $db->Quote( $now  ) . " )"
				. ( ( !$mainframe->getCfg( 'shownoauth' ) ) ? "\n AND a.access <= " . (int) $aid : '' )
		;
		
		$query .=  $condition . ' ORDER BY ' . $ordering;
		$query .=  $limit ? ' LIMIT ' . $limit : '';
		$db->setQuery($query);
		
		return $db->loadObjectlist();		
	}
	
	/**
	 * load css - javascript file.
	 */
	public static function loadMediaFiles( $params, $module ){
		// if the verion is equal 1.6.x
		if( JVersion::isCompatible('1.6.0') ) {	
			JHTML::script( $module->module.'_jl16x.js','modules/'.$module->module.'/assets/');
		} else {
			JHTML::script( $module->module.'_jl15x.js','modules/'.$module->module.'/assets/');
		}
		JHTML::stylesheet( $module->module.'.css','modules/'.$module->module.'/assets/' );	
	}
	
	/**
	 * render text displaying. 
	 */
	public static function renderText( $formatter, $row, $openTarget, $sp=" > " ){
		// echo '<pre>'.print_r( $row,1 ); die;
		$title = '<a target="_'.$openTarget.'" href="'.$row->link.'" title="'.$row->title.'">'
					. $row->subtitle	. "</a>";
		switch( $formatter ){
			case 'title-created':
				return  $title . $sp . " " . $row->created;
			case 'title-description':
				return  $title . $sp . " " . $row->description;
			case 'title-description':
				return  $title . $sp . " " . $row->description;
			case 'title-description-created':
				return $title . $sp . " " . $row->description . " " 
						. '<span>' . $row->created .'</span>';	
			case 'category-title':		
				return  $row->category_title 
						. ': '. $title . $sp 
						. ' <span>' . $row->created .'</span>';	
			default:
				return $title;
		}
	}
	
	public static function substring( $text, $length = 100, $replacer='...' ){
		$string = strip_tags( $text );
		if( function_exists('mb_substr') ){
			if(  $length > mb_strlen($string) ) return $string; 
			return (preg_match('/^(.*)\W.*$/', 
						mb_substr($string, 0, $length+1), $matches) 
							? $matches[1] : mb_substr($string, 0, $length)) . $replacer; 
		} 
		if(  $length > strlen($string) ) return $string; 
		return (preg_match('/^(.*)\W.*$/', 
					substr($string, 0, $length+1), $matches) 
						? $matches[1] : substr($string, 0, $length)) . $replacer; 
	}
}
?>